package cn.com.dhcc.turbo.service.monitor.gather;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.YESNO;
import cn.com.dhcc.app.core.util.StorageResourcesUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.service.TurboFtpClientFactory;
import cn.com.dhcc.app.pub.core.util.FtpUtil;
import cn.com.dhcc.app.pub.core.util.HttpUtil;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.service.exch.DistributedNodeInfoService;
import cn.com.dhcc.turbo.service.monitor.MonitorService;
import cn.com.dhcc.turbo.service.monitor.QUOTA;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.registry.NodePipelineService;
import cn.com.dhcc.turbo.service.registry.vo.PipeLineFtp;

/**
 * ftp 监控指标的状态
 * @author qiao
 * @2014-9-12 @下午3:09:56
 */
@Service
public class FtpServerQuotaGatherService {

	
	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(LOGTYPE.MONITOR);
	
	@Autowired
	private MonitorService monitorService;
	@Autowired 
	BaseInfoService baseInfoService;
	@Autowired
	NodePipelineService nodePipelineService;
	@Autowired
	private NodeInfoService nodeInfoService;
	@Autowired
	private DistributedNodeInfoService  distributedNodeInfoService;
	/**
	 * 	FTP_CONN_STATUS("节点FTP连接状态"),
	 */
	public void ftpConnStatus(){
		QUOTA quota = QUOTA.FTP_CONN_STATUS;
		QUOTA remoteQuota = QUOTA.REMOTE_FTP_CONN_STATUS;
		logger.info("开始收集指标["+quota.getDesc()+"]...");
		Date now = new Date();
		try {
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			if(localNode==null){
				logger.error("指标["+quota.getDesc()+"]值收集失败：节点未初始化...");
				return;
			}
			List<NodeInfo> list = nodeInfoService.getAllLocalExchNodeList(localNode.getId());
			if(list.size() == 0){
				list.add(localNode);
			}
			for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
				NodeInfo nodeInfo = iterator.next();
				QuotaValueOnTime onTime = new QuotaValueOnTime();
				String status = "1";
				 if(HttpUtil.checkUrl(nodeInfo.getInstallUrl())){
					String nodecode = nodeInfo.getNodeCode();
					PipeLineFtp ftp = distributedNodeInfoService.getFtpPipeLineByNodeCode(nodecode);
					if(ftp == null) continue;
					String host = ftp.getIp();//发送目的服务器的地址
					String tousername = AppConst.EMBFTP.EMBFTP_ADMIN_USERID;//发送目的服务器的ftp用户名
					String topassword = AppConst.EMBFTP.EMBFTP_ADMIN_PWD;//发送目的服务器的ftp密码
					int port = ftp.getPort();
					FTPClient ftpClient = TurboFtpClientFactory.createFtpClient();
					
					boolean canLogin = false;
					try {
						canLogin = FtpUtil.login(ftpClient, host, tousername, topassword+" "+topassword+" "+AppConst.getAdminAuthCode(), port);
						if(canLogin){
							FtpUtil.logout(ftpClient);
						}
					} catch (Exception e) {
						//
					}
					if(!canLogin){
						status = "0";
					}
				 }
				
				 if(localNode.getId().equals(nodeInfo.getId())){
					 	onTime.setOwnerId(nodeInfo.getId());
						onTime.setQuotaCode(quota.getCode());
					}else{
						onTime.setOwnerId(localNode.getId()+"|"+nodeInfo.getId());
						onTime.setQuotaCode(remoteQuota.getCode());
					}
				onTime.setCurrentValue1(status);
				onTime.setCanMerge(YESNO.YES.getStatus());
				onTime.setId(UUIDGenerator.getUUID());
				onTime.setMtime(now);
			
				monitorService.insertOrUpdateQuotaOnTime(onTime);
				logger.info("指标["+quota.getDesc()+"]值收集结束，值为："+status);
			}
		} catch (Exception e) {
			logger.error("指标["+quota.getDesc()+"]值收集失败",e);
		}
	}
	/**
	 * 	FTP_FS_USED_RATE("节点FTP文件系统使用率"),
	 */
	public void ftpUsedRate(){
		
		QUOTA quota = QUOTA.FTP_FS_USED_RATE;
		logger.info("开始收集指标["+quota.getDesc()+"]...");
		Date now = new Date();
		try {
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			PipeLineFtp pipeLineFtp = nodePipelineService.getLocalFtpConf();
			if(localNode==null){
				logger.error("指标["+quota.getDesc()+"]值收集失败：节点未初始化...");
				return;
			}
			//收集指标REGIST_SYS_NUM("regist_sys_num","注册系统数量"),
			String homeDir =pipeLineFtp==null?"":pipeLineFtp.getRootDir();
			int usedRate = StorageResourcesUtil.getFileSystemUsedRate(homeDir);
			QuotaValueOnTime onTime = new QuotaValueOnTime();
			onTime.setCanMerge(YESNO.YES.getStatus());
			onTime.setCurrentValue1(usedRate+"");
			onTime.setId(UUIDGenerator.getUUID());
			onTime.setMtime(now);
			onTime.setQuotaCode(quota.getCode());
			onTime.setOwnerId(localNode.getId());
			monitorService.insertOrUpdateQuotaOnTime(onTime);
			logger.info("指标["+quota.getDesc()+"]值收集结束，值为："+usedRate+"%");
		} catch (Exception e) {
			logger.error("指标["+quota.getDesc()+"]值收集失败",e);
		}
	}
	
}
